#include "ImageManager.h"
#include "Base/Logger.h"

ImageManager ImageManager::singleton;

sf::Texture *ImageManager::GetImage(const std::string &ImageLink)
{
    sf::Texture *ImgTemp;

    if(!SearchImage(ImageLink, ImgTemp))
    {
        ImgTemp = CreateImage(ImageLink);
		ImgTemp->setSmooth(false);
		BPL::Logger::log(("Image '" + ImageLink + "'added").c_str());
    }

    return ImgTemp;
}

void ImageManager::DeleteImage(sf::Texture &Img)
{
    std::map<std::string, sf::Texture*>::iterator it;

    for(it = Images.begin(); it != Images.end(); it++)
    {
        if(it->second == &Img)
        {
            delete &Img;
            Images.erase(it);
            break;
        }
    }
}

void ImageManager::DeleteImage(const std::string& ImageLink)
{
    std::map<std::string, sf::Texture*>::iterator it;

    it = Images.find(ImageLink);

    if(it != Images.end())
    {
        if(it->second != NULL)
        {
            delete (it->second);
            Images.erase(it);
        }
    }
}

bool ImageManager::SearchImage(const std::string &ImageLink, sf::Texture* &ImgTemp)
{
    std::map<std::string, sf::Texture*>::iterator it;

    it = Images.find(ImageLink);

    if(it == Images.end())
    {
        return false;
    }
    else
    {
        ImgTemp = it->second;
    }

    return true;
}

sf::Texture *ImageManager::CreateImage(const std::string &ImageLink)
{
    sf::Texture *ImgTemp = new sf::Texture();
    if(ImgTemp->loadFromFile(ImageLink))
    {
		ImgTemp->setSmooth(false);
        Images.insert(std::make_pair(ImageLink, ImgTemp));
        return ImgTemp;
    }
    else
    {
        delete ImgTemp;
    }

    return NULL;
}

ImageManager::ImageManager()
{

}

ImageManager::~ImageManager()
{
    std::map<std::string, sf::Texture*>::iterator it;
    for(it = Images.begin(); it != Images.end(); it++)
    {
        delete it->second;
    }
}

ImageManager::ImageManager(const ImageManager&)
{

}

ImageManager& ImageManager::operator= (const ImageManager&)
{
	return *this;
}


